package cn.itcast.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        判断是否有登录人：判断每次请求中是否有一个token的请求参数
//        如果有这个参数代表有登录人，放行进入到后面的微服务中
//        如果没有这个参数代表没有登录人直接返回一个401或者403的状态码
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getQueryParams().getFirst("token");
        if(StringUtils.isNotBlank(token)){  //token不为空
            return chain.filter(exchange);
        }else{
            //token为空
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete(); //返回给浏览器
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
